﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Trackr.Core.DataProvider.SQL
{
	public class Insert : IQuery
	{
		private StringBuilder _sql = new StringBuilder(1024);
		private List<string> _filterParams = new List<string>();
		private Dictionary<string, object> _setValues = new Dictionary<string, object>();
		private string _tableName = string.Empty;

		public Insert(string tableName)
		{
			this._tableName = tableName;
		}
		public Insert Set(string key, string value)
		{
			_setValues.Add(key, value);
			return this;
		}
		public Insert Set(Dictionary<string, object> keyValuePair)
		{
			foreach (var keyVal in keyValuePair)
			{
				_setValues.Add(keyVal.Key, keyVal.Value);
			}
			return this;
		}
		public Insert Where(string key, Operator op, string value)
		{
			_filterParams.Add(string.Format("{0} {1} {2}", key, Enums.GetOperator(op), value));
			return this;
		}
		public Insert And(string key, Operator op, string value)
		{
			_filterParams.Add(string.Format("{0} {1} {2}", key, Enums.GetOperator(op), value));
			return this;
		}

		public string ToSql()
		{
			_sql.Clear();
			_sql.Append(string.Format("INSERT INTO {0}", _tableName));
			if (_setValues.Count > 0)
			{
				string[] columns = _setValues.Select(k => k.Key).ToArray();
				_sql.Append(" ( " + string.Join(", ", columns) + " ) ");
				_sql.Append(" VALUES ");
				string[] values = _setValues.Select(k => string.Format("'{0}'", k.Value)).ToArray();
				_sql.Append(" ( " + string.Join(", ", values) + " ) ");
			}
			if (_filterParams.Count > 0)
			{
				_sql.Append(" WHERE ");
				_sql.Append(string.Join(" AND ", _filterParams.ToArray()));
			}
			return _sql.ToString().Trim();
		}
		public override string ToString()
		{
			return ToSql();
		}
	}
}
